using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using DatabaseManager.Models;
using DatabaseManager.Services;
using DatabaseManager.Filters;

namespace DatabaseManager.Controllers;

/// <summary>
/// 数据库管理控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[ServiceFilter(typeof(AdminAuthorizationFilter))]
public class DatabaseManagementController : ControllerBase
{
    private readonly DatabaseManagementService _dbService;
    private readonly ILogger<DatabaseManagementController> _logger;

    public DatabaseManagementController(ILogger<DatabaseManagementController> logger, DatabaseManagementService dbService)
    {
        _logger = logger;
        _dbService = dbService;
    }

    #region 账号管理 API

    /// <summary>
    /// 获取所有账号
    /// </summary>
    [HttpGet("accounts")]
    public async Task<IActionResult> GetAllAccounts()
    {
        try
        {
            var accounts = await _dbService.GetAllAccountsAsync();
            return Ok(ApiResult<object>.SuccessResult(accounts));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取账号列表失败");
            return BadRequest(ApiResult<object>.FailResult($"获取账号列表失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 获取账号详情
    /// </summary>
    [HttpGet("accounts/{loginName}")]
    public async Task<IActionResult> GetAccount(string loginName)
    {
        try
        {
            var account = await _dbService.GetAccountAsync(loginName);
            if (account == null)
            {
                return NotFound(ApiResult<object>.FailResult("账号不存在"));
            }

            return Ok(ApiResult<object>.SuccessResult(account));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取账号详情失败: {LoginName}", loginName);
            return BadRequest(ApiResult<object>.FailResult($"获取账号详情失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 创建账号
    /// </summary>
    [HttpPost("accounts")]
    public async Task<IActionResult> CreateAccount([FromBody] CreateAccountRequest request)
    {
        try
        {
            // 检查账号是否已存在
            if (await _dbService.AccountExistsAsync(request.LoginName))
            {
                return BadRequest(ApiResult<object>.FailResult("账号已存在"));
            }

            var result = await _dbService.CreateAccountAsync(request);
            return Ok(ApiResult<object>.SuccessResult(result, "账号创建成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建账号失败: {LoginName}", request.LoginName);
            return BadRequest(ApiResult<object>.FailResult($"创建账号失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 删除账号
    /// </summary>
    [HttpDelete("accounts/{loginName}")]
    public async Task<IActionResult> DeleteAccount(string loginName)
    {
        try
        {
            // 检查账号是否存在
            if (!await _dbService.AccountExistsAsync(loginName))
            {
                return NotFound(ApiResult<object>.FailResult("账号不存在"));
            }

            var result = await _dbService.DeleteAccountAsync(loginName);
            return Ok(ApiResult<object>.SuccessResult(result, "账号删除成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除账号失败: {LoginName}", loginName);
            return BadRequest(ApiResult<object>.FailResult($"删除账号失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    [HttpPut("accounts/change-password")]
    public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
    {
        try
        {
            // 检查账号是否存在
            if (!await _dbService.AccountExistsAsync(request.LoginName))
            {
                return NotFound(ApiResult<object>.FailResult("账号不存在"));
            }

            var result = await _dbService.ChangePasswordAsync(request);
            return Ok(ApiResult<object>.SuccessResult(result, "密码修改成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "修改密码失败: {LoginName}", request.LoginName);
            return BadRequest(ApiResult<object>.FailResult($"修改密码失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 启用/禁用账号
    /// </summary>
    [HttpPut("accounts/{loginName}/status")]
    public async Task<IActionResult> ToggleAccountStatus(string loginName, [FromQuery] bool disable)
    {
        try
        {
            // 检查账号是否存在
            if (!await _dbService.AccountExistsAsync(loginName))
            {
                return NotFound(ApiResult<object>.FailResult("账号不存在"));
            }

            var result = await _dbService.ToggleAccountStatusAsync(loginName, disable);
            var message = disable ? "账号已禁用" : "账号已启用";
            return Ok(ApiResult<object>.SuccessResult(result, message));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "修改账号状态失败: {LoginName}", loginName);
            return BadRequest(ApiResult<object>.FailResult($"修改账号状态失败: {ex.Message}"));
        }
    }

    #endregion

    #region 数据库管理 API

    /// <summary>
    /// 获取所有数据库
    /// </summary>
    [HttpGet("databases")]
    public async Task<IActionResult> GetAllDatabases()
    {
        try
        {
            var databases = await _dbService.GetAllDatabasesAsync();
            return Ok(ApiResult<object>.SuccessResult(databases));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取数据库列表失败");
            return BadRequest(ApiResult<object>.FailResult($"获取数据库列表失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 获取数据库详情
    /// </summary>
    [HttpGet("databases/{databaseName}")]
    public async Task<IActionResult> GetDatabase(string databaseName)
    {
        try
        {
            var database = await _dbService.GetDatabaseAsync(databaseName);
            if (database == null)
            {
                return NotFound(ApiResult<object>.FailResult("数据库不存在"));
            }

            return Ok(ApiResult<object>.SuccessResult(database));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取数据库详情失败: {DatabaseName}", databaseName);
            return BadRequest(ApiResult<object>.FailResult($"获取数据库详情失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 创建数据库
    /// </summary>
    [HttpPost("databases")]
    public async Task<IActionResult> CreateDatabase([FromBody] CreateDatabaseRequest request)
    {
        try
        {
            // 检查数据库是否已存在
            if (await _dbService.DatabaseExistsAsync(request.DatabaseName))
            {
                return BadRequest(ApiResult<object>.FailResult("数据库已存在"));
            }

            var result = await _dbService.CreateDatabaseAsync(request);
            return Ok(ApiResult<object>.SuccessResult(result, "数据库创建成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建数据库失败: {DatabaseName}", request.DatabaseName);
            return BadRequest(ApiResult<object>.FailResult($"创建数据库失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 删除数据库
    /// </summary>
    [HttpDelete("databases/{databaseName}")]
    public async Task<IActionResult> DeleteDatabase(string databaseName)
    {
        try
        {
            // 检查数据库是否存在
            if (!await _dbService.DatabaseExistsAsync(databaseName))
            {
                return NotFound(ApiResult<object>.FailResult("数据库不存在"));
            }

            var result = await _dbService.DeleteDatabaseAsync(databaseName);
            return Ok(ApiResult<object>.SuccessResult(result, "数据库删除成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除数据库失败: {DatabaseName}", databaseName);
            return BadRequest(ApiResult<object>.FailResult($"删除数据库失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 获取数据库大小
    /// </summary>
    [HttpGet("databases/{databaseName}/size")]
    public async Task<IActionResult> GetDatabaseSize(string databaseName)
    {
        try
        {
            var size = await _dbService.GetDatabaseSizeAsync(databaseName);
            return Ok(ApiResult<object>.SuccessResult(new { DatabaseName = databaseName, SizeMB = size }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取数据库大小失败: {DatabaseName}", databaseName);
            return BadRequest(ApiResult<object>.FailResult($"获取数据库大小失败: {ex.Message}"));
        }
    }

    #endregion

    #region 权限管理 API

    /// <summary>
    /// 获取账号的数据库权限
    /// </summary>
    [HttpGet("permissions/accounts/{loginName}")]
    public async Task<IActionResult> GetAccountPermissions(string loginName, [FromQuery] string? databaseName = null)
    {
        try
        {
            var permissions = await _dbService.GetAccountPermissionsAsync(loginName, databaseName);
            return Ok(ApiResult<object>.SuccessResult(permissions));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取账号权限失败: {LoginName}", loginName);
            return BadRequest(ApiResult<object>.FailResult($"获取账号权限失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 获取数据库的所有用户权限
    /// </summary>
    [HttpGet("permissions/databases/{databaseName}")]
    public async Task<IActionResult> GetDatabasePermissions(string databaseName)
    {
        try
        {
            var permissions = await _dbService.GetDatabasePermissionsAsync(databaseName);
            return Ok(ApiResult<object>.SuccessResult(permissions));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取数据库权限失败: {DatabaseName}", databaseName);
            return BadRequest(ApiResult<object>.FailResult($"获取数据库权限失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 授予权限
    /// </summary>
    [HttpPost("permissions/grant")]
    public async Task<IActionResult> GrantPermission([FromBody] GrantPermissionRequest request)
    {
        try
        {
            // 检查账号是否存在
            if (!await _dbService.AccountExistsAsync(request.LoginName))
            {
                return NotFound(ApiResult<object>.FailResult("账号不存在"));
            }

            // 检查数据库是否存在
            if (!await _dbService.DatabaseExistsAsync(request.DatabaseName))
            {
                return NotFound(ApiResult<object>.FailResult("数据库不存在"));
            }

            var result = await _dbService.GrantPermissionAsync(request);
            return Ok(ApiResult<object>.SuccessResult(result, "权限授予成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "授予权限失败: {LoginName} -> {DatabaseName}", 
                request.LoginName, request.DatabaseName);
            return BadRequest(ApiResult<object>.FailResult($"授予权限失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 撤销权限
    /// </summary>
    [HttpPost("permissions/revoke")]
    public async Task<IActionResult> RevokePermission([FromBody] RevokePermissionRequest request)
    {
        try
        {
            // 检查账号是否存在
            if (!await _dbService.AccountExistsAsync(request.LoginName))
            {
                return NotFound(ApiResult<object>.FailResult("账号不存在"));
            }

            // 检查数据库是否存在
            if (!await _dbService.DatabaseExistsAsync(request.DatabaseName))
            {
                return NotFound(ApiResult<object>.FailResult("数据库不存在"));
            }

            var result = await _dbService.RevokePermissionAsync(request);
            return Ok(ApiResult<object>.SuccessResult(result, "权限撤销成功"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "撤销权限失败: {LoginName} -> {DatabaseName}", 
                request.LoginName, request.DatabaseName);
            return BadRequest(ApiResult<object>.FailResult($"撤销权限失败: {ex.Message}"));
        }
    }

    /// <summary>
    /// 检查账号是否有特定数据库的访问权限
    /// </summary>
    [HttpGet("permissions/check")]
    public async Task<IActionResult> CheckPermission([FromQuery] string loginName, [FromQuery] string databaseName)
    {
        try
        {
            var hasPermission = await _dbService.HasPermissionAsync(loginName, databaseName);
            return Ok(ApiResult<object>.SuccessResult(new { 
                LoginName = loginName, 
                DatabaseName = databaseName, 
                HasPermission = hasPermission 
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "检查权限失败: {LoginName} -> {DatabaseName}", loginName, databaseName);
            return BadRequest(ApiResult<object>.FailResult($"检查权限失败: {ex.Message}"));
        }
    }

    #endregion
}